*********************************
* CODE USED TO GENERATE WEIGHTED AVERAGES OF BILATERAL MIRROR TRADE FLOWS
*********************************

*********************
* ADD CIF DYAD-MEANS TO IMF-DOTS
*********************

use imfdotsmirror-uni

generate cowcodeAuni_forid=cowcodeAuni*1000
generate dyadid_cow=cowcodeAuni_forid+cowcodeBuni
browse cowcodeAuni cowcodeBuni year dyadid_cow

merge m:1 dyadid_cow using cif_dyadmeans

drop if _merge==2

drop countryA_name countryB_name _merge cowcodeAuni_forid

save as imfdotsmirror-uni-wgtavgs


*************************
* Generate FOBs of flow1s
*************************

use imfdotsmirror-uni-wgtavgs

generate fob_conversionfct=(1-cifrate_mean)

generate imf_flow1_fob=(imf_flow1_uni*fob_conversionfct)

browse countryA_name countryB_name year imf_flow1_uni imf_flow1_fob imf_flow1mirror_uni cifrate_mean

*save

************************
* calculate ABBAs
************************

generate abba_fob=(imf_flow1_fob-imf_flow1mirror_uni)
generate abbabs_fob=abs(abba_fob)

replace abba_fob=. if pr_imf_flow1_uni==1
replace abba_fob=. if pr_imf_flow1mirror_uni==1

generate abba_mirrorsum=(abbabs_fob/(imf_flow1_fob+imf_flow1mirror_uni))

***********************
* generate weighted averages
***********************

use imfdotsmirror-uni-wgtavgs

generate cowA_forid=cowcodeAuni*10000
generate countryAyear=cowA_forid+year

sort countryAyear
by countryAyear: egen abba_medianA=median(abba_mirrorsum)

* same for B

generate cowB_forid=cowcodeBuni*10000
generate countryByear=cowB_forid+year

sort countryByear
by countryByear: egen abba_medianB=median(abba_mirrorsum)

*
generate diff_abbamedian=abs(abba_medianA-abba_medianB)

*

generate cwgtA=.
replace cwgtA=(0.5+(diff_abbamedian/2)) if abba_medianA<=abba_medianB
replace cwgtA=(0.5-(diff_abbamedian/2)) if abba_medianA>abba_medianB

generate cwgtB=.
replace cwgtB=(0.5+(diff_abbamedian/2)) if abba_medianB<=abba_medianA
replace cwgtB=(0.5-(diff_abbamedian/2)) if abba_medianB>abba_medianA

generate cwgtsum=cwgtA+cwgtB

*

generate flow1_wgtavg=(cwgtA*imf_flow1_fob)+(cwgtB*imf_flow1mirror_uni)

browse countryA_name_uni countryB_name_uni year imf_flow1_fob imf_flow1mirror_uni abba_medianA abba_medianB cwgtA cwgtB flow1_wgtavg

replace flow1_wgtavg=. if pr_imf_flow1_uni==1
replace flow1_wgtavg=. if pr_imf_flow1mirror_uni==1

save, replace

*

rename flow1 flowBAA
rename flow1_mirror flowBAB
rename flow1_wgtavg flowWAV

keep cowcodeA cowcodeB countryA_name countryB_name year flowBAA flowBAB flowWAV

save, replace

******
* END
******
